package com.example.springboot.task;

import com.example.springboot.entity.vo.PostVo;
import com.example.springboot.service.PostService;
import com.example.springboot.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class RedisTask {
    private static final Logger logger = LoggerFactory.getLogger(RedisTask.class);
    @Autowired
    private PostService postService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
@Autowired
    private RedisUtil redisUtil;
    /**
     * 每天凌晨3点，更新排行榜信息
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void executeTask() {
        logger.info("定时任务执行: {}", new java.util.Date());

        clearAndInsertRankings("views");
        clearAndInsertRankings("likes");
        clearAndInsertRankings("collectCount");
    }
    private void clearAndInsertRankings(String rankingType) {
        // 根据排行类型获取排行数据
        List<PostVo> rankings = postService.getRankingsByType(rankingType);

        // 清空 Redis 中对应排行榜的数据
        Set<String> keysToDelete = redisTemplate.keys("postRanking:" + rankingType + ":*");
        if (!keysToDelete.isEmpty()) {
            redisTemplate.delete(keysToDelete);
        }
        redisUtil.del(rankingType);
        // 存储新的排行数据到 Redis
        for (PostVo postVo : rankings) {
            String key = "postRanking:" + rankingType + ":" + postVo.getId();
            redisTemplate.opsForZSet().add(rankingType, key, getValueForRankingType(postVo, rankingType)); // 使用有序集合存储，按指定类型排序
            redisTemplate.opsForValue().set(key, postVo); // 存储具体内容
        }
    }
    // 根据排行类型返回对应的值
    private double getValueForRankingType(PostVo postVo, String rankingType) {
        switch (rankingType) {
            case "views":
                return postVo.getViews();
            case "likes":
                return postVo.getLikes();
            case "collectCount":
                return postVo.getCollectCount();
            default:
                return 0; // 默认情况下，可以返回一个默认值或者抛出异常
        }
    }
}
